import os
import uuid

from werkzeug.datastructures import FileStorage
from config import ALLOWED_EXTENSIONS
from config import UPLOAD_FOLDER


def allowed_file(filename: str):
    """
    检查用户上传的文件类型是否是允许的。
    :param filename:
    :return: boolean
    """
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def get_ext(filename: str):
    """
    获取用户上传文件的文件类型
    :param filename: 文件名称
    :return: str
    """
    return filename.rsplit('.', 1)[1].lower()


def get_new_filename(filename: str):
    """
    安全考虑生成随机文件名
    :param 传入文件名
    :return: 如：ac753206f7a348f196826475c577a95d.jpg
    """
    # 获取后缀名
    ext = filename.rsplit('.', 1)[1].lower()
    # 转换为安全文件名
    unique_filename = str(uuid.uuid4())
    unique_filename = unique_filename.replace('-', '')
    return unique_filename + '.' + ext


def save_photo(file_storage: FileStorage):
    """
    保存用户上传的图片
    :param file_storage: 上传文件对象
    :return: 返回文件保存绝对路径
    """
    new_filename = get_new_filename(file_storage.filename)
    file_full_path = os.path.join(UPLOAD_FOLDER, new_filename)
    mkdir(UPLOAD_FOLDER)
    file_storage.save(file_full_path)
    return file_full_path


def make_api_response(status: int,
                      msg: str,
                      plate='',
                      confidence=0.0,
                      location=None,
                      img_size=0,
                      use_time=0,
                      result_photo='',
                      img_name=''):
    """
    根据参数生成接口数据结构
    :param result_photo: 图片地址
    :param img_name: 上传的图片名称
    :param use_time: 识别用时
    :param img_size: 图片大小
    :param status: 接口状态。0表示成功，1表示失败
    :param msg: 提示信息
    :param plate: 车牌号码
    :param confidence: 可信度
    :param location: 像素位置列表
    :return:
    """

    if location is None:
        location = []
    api_response = {
        'status': status if status in [0, 1] else 1,
        'message': msg,
        'plate': plate,
        'confidence': confidence,
        'location': location,
        'used_time': use_time,
        'result_photo': result_photo,
        'img_size': img_size,
        'img_name': img_name,
    }

    return api_response


def mkdir(path):
    """
    创建文件夹
    """
    folder = os.path.exists(path)
    if not folder:
        os.makedirs(path)
